import * as cheerio from 'cheerio';
import { Novel } from './models/novel';
import { Chapter } from './models/chapter';
import { config } from './config';

export class Parser {
    parseNovelInfo(html: string, url: string, webSite: string): Novel {
        const $ = cheerio.load(html);
        const selectors = config.parser[webSite as keyof typeof config.parser];
        const title = $(selectors.title).text().trim();
        const author = $(selectors.author).text().trim();
        const descriptionEl = $(selectors.description);
        let description = descriptionEl.is('meta') ? descriptionEl.attr('content') || '' : descriptionEl.text().trim();
        description = this.cleanDescription(description);
        const coverUrl = $(selectors.cover).attr('src');
        const chapterList: string[] = [];
        $(selectors.chapterList).each((_, element) => {
            const href = $(element).attr('href');
            console.log(`Found chapter URL: ${href}`);
            if (href) {
                const chapterUrl = new URL(href, url).toString();
                chapterList.push(chapterUrl);
            }
        });
        return {
            url,
            title,
            author,
            description,
            coverUrl,
            chapterList
        };
    }
    
    parseChapterList(html: string, url: string, novel: Novel, webSite: string): Novel {
        const $ = cheerio.load(html);
        const selectors = config.parser[webSite as keyof typeof config.parser];
        const chapterList: string[] = [];
        $(selectors.chapterList).each((_, element) => {
            const href = $(element).attr('href');
            console.log(`Found chapter URL from chaptersUrl: ${href}`);
            if (href) {
                const chapterUrl = new URL(href, url).toString();
                chapterList.push(chapterUrl);
            }
        });
        console.log(`从章节列表页面解析到 ${chapterList.length} 个章节`);
        return {
            ...novel,
            chapterList
        };
    }

    parseChapter(html: string, url: string, novelUrl: string, index: number, webSite: string): Chapter {
        const $ = cheerio.load(html);
        const selectors = config.parser[webSite as keyof typeof config.parser];
        let title = $(selectors.chapterTitle).text().trim();
        title = title.replace(/章节评论段评$/, '');

        let content = '';
        if (webSite === 'zongheng') {
            $('p').each((_, element) => {
                const text = $(element).text().trim();
                if (!['下下下', '载载载', '纵纵纵', '横横横', '小小小', '说说说', '看全文'].includes(text)) {
                    content += `${text}\n\n`;  // 改为双换行符模拟段落间距
                }
            });
        } else {
            // 通用处理：获取纯文本并用换行符格式化
            content = $(selectors.chapterContent)
                .text()
                .replace(/\n\s+/g, '\n')    // 清理多余空白
                .replace(/(\S)\n(\S)/g, '$1\n\n$2'); // 在段落间添加换行
        }
        
        // 清理残留HTML标签和广告文本
        content = this.cleanContent(content);
        return {
            url,
            title,
            content: content.trim(),  // 移除首尾空白
            novelUrl,
            index
        };
    }

    private cleanContent(content: string): string {
        // 修改为纯文本清理逻辑
        return content
            .replace(/<[^>]+>/g, '')          // 移除所有HTML标签
            .replace(/\s{2,}/g, '\n')         // 多个空格转单换行
            .replace(/(\n\s*){3,}/g, '\n\n') // 多个空行合并为双换行
            .replace(/(下下下|载载载|纵纵纵|横横横|小小小|说说说|看全文)/g, '')
            .replace(/扫一扫·\s*手机接着看/g, '')
            .replace(/公交地铁随意阅读，新用户享超额福利/g, '');
    }

    private cleanDescription(description: string): string {
        if (description.startsWith('content="')) {
            description = description.substring('content="'.length);
            if (description.endsWith('"')) {
                description = description.substring(0, description.length - 1);
            }
        }

        const novelIntroPattern = /观看小说：(.+)$/;
        const match = description.match(novelIntroPattern);
        if (match && match[1]) {
            description = match[1];
        }

        description = description
            .replace(/纵横小说网提供作者\(.+?\)的经典小说《.+?》，/g, '')
            .replace(/《.+?》最新章节全文阅读服务，/g, '')
            .replace(/本站更新及时，无弹窗广告，欢迎光临\(.+?\)/g, '')
            .replace(/m\.zongheng\.com/g, '')
            .replace(/www\.zongheng\.com/g, '');

        description = description
            .replace(/&nbsp;/g, ' ')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&amp;/g, '&')
            .replace(/&quot;/g, '"')
            .replace(/&#39;/g, "'");

        return description.trim();
    }
}